<template>
    <j-modal
            :width="modalWidth"
            :visible="visible"
            :title="title"
            switchFullscreen
            @ok="handleSubmit"
            @cancel="close"
            style="top:50px"
            cancelText="关闭"
    >
        <a-tabs :active-key="activeKey" @tabClick="tabClick">
            <a-tab-pane key="3" tab="负责人">
                    <SelectPositioncust ref="SelectPosition" :termCustCode.sync="custCode" :current-data.sync="positionsData" :visible="visible"/>
            </a-tab-pane>
        </a-tabs>

    </j-modal>
</template>

<script>
    import {filterObj} from '@/utils/util'
    import {getAction, postAction} from "@/api/manage";
    import JInput from '@/components/cn-form/JInput.vue';
    import SelectPositioncust from '@/components/cn-components/select-positioncust'
    import {PageListMixin} from '@/mixins/PageListMixin'

    export default {
        name: 'dealer-white-modal',
        components: {JInput,SelectPositioncust},
        props: ['modalWidth', 'multi', 'userIds'],
        data() {
            return {
                typeLoading:false,
                queryParam: {
                    code: "",
                    name: "",
                },
                custCode:'',
                positionsData:[],
                treeData: [],
                scrollTrigger: {},
                selectedRowKeys: [],
                selectUserRows: [],
                selectUserIds: [],
                title: '职位配置',
                selectedKeys: [],
                visible: false,
                form: this.$form.createForm(this),
                loading: false,
                expandedKeys: [],
                reqCode: '',
                activeKey: '3',
                url: {
                    list:  window._CONFIG['domianURL'] + '/customerController/getPositionListByCust',
                    selected:  window._CONFIG['domianURL'] + '/customerController/getSelectPositionListByCust'
                },
                record:null
            }
        },
        mixins: [PageListMixin],
        computed: {
            // 计算属性的 getter
            getType: function () {
                return this.multi == true ? 'checkbox' : 'radio';
            }
        },
        watch: {
            visible(v) {
                if (v) {
                    this.$nextTick(()=>{

                        if (this.activeKey == '1') {
                            this.queryDepartTree();
                        } else if (this.activeKey == '2') {
                            this.loadData()
                        }else if (this.activeKey == '3') {
                            if(this.$refs.SelectPosition)this.$refs.SelectPosition.loadData(1)
                        }
                    })
                }
            },
            activeKey() {
                if (this.activeKey == '1') {
                    this.queryDepartTree();
                } else if (this.activeKey == '2') {
                    this.loadData()
                }else if (this.activeKey == '3') {
                    if(this.$refs.SelectPosition)this.$refs.SelectPosition.loadData(1)
                }
            },
            // reqCode() {
            //     this.getSelectdData()
            // }
        },
        created() {
            // 该方法触发屏幕自适应
            this.resetScreenSize();
        },
        methods: {


            /**
             * 获取已选中数据
             */
            getSelectdData() {
                this.custCode = this.reqCode
                postAction(this.url.selected, {custCode: this.reqCode}).then(res => {
                    const {result} = res
                    this.record = result
                    if (result && result&& result.length) {
                        // 1:与经销商关系 2:标签，3，与商品类型关系，4与商品关系
                        this.positionsData = result.map(position=>Object.assign(position,{
                            positionCode:position.positionCode,
                            positionName:position.positionName,
                        }))
                    }
                })
            },

            /**
             * 删除已选中商品
             * @param record
             */
            handleDelete(record) {
                this.selectionRows.remove(record)
                this.selectedRowKeys.remove(record['code'])
            },
            /**
             * 标签页的选中事件
             * @param name
             */
            tabClick(name) {
                this.activeKey = name
            },
            /**
             * 递归树结构数据，取出所有子元素
             * @param children
             * @param selected
             * @returns {*}
             */
            getAllChildren(children, selected) {
                if (children && children.length) {
                    children.map(child => {
                        selected.push(child)
                        this.getAllChildren(child.children, selected)
                    })
                }
                return selected
            },
            /**
             * 选中树节点操作
             * @param checkedKeys
             * @param checked 不等于undefined 表示当前事件为checkbox事件，否则为点击树节点事件
             * @param checkedNodes
             * @param node
             * @param event
             */
            handleCheckbox(checkedKeys, {checked, checkedNodes, node, event}) {
                if (checked !== undefined) {
                    //todo 当事件为checkbox事件时，checkedKeys当前选中的数据包含自节点数据
                    this.selectedKeys = checkedKeys
                    this.categoryData = this.getAllChildren(this.treeData, []).filter(node => checkedKeys.includes(node.code)).map(node =>
                        Object.assign({}, node, {
                            children: null
                        }))
                } else {
                    //todo 当事件为nodeClick事件时，checkedKeys当前选中数据为当前点击节点
                    const checkNodes = [node.dataRef, ...this.getAllChildren(node.dataRef.children, [])]
                    //todo 如果当前点击节点已经被选中，则执行删除操作
                    if (this.selectedKeys.includes(node.dataRef.code)) {
                        checkNodes.map(node => {
                            this.selectedKeys.remove(node.code)
                            //todo 从右边table删除选中数据
                            this.categoryData.remove(node)
                        })
                    } else {
                        this.selectedKeys = Array.from(new Set(this.selectedKeys.concat(checkNodes.map(node => node.code))));
                        //todo 添加选中数据到右边table
                        this.categoryData = Array.from(new Set([...this.categoryData, ...checkNodes.map(node => Object.assign({}, node, {
                            children: null
                        }))]));
                    }

                }
            },
            /**
             * 覆盖mixin的loadData方法
             * @param arg
             * @returns {Promise<void>}
             */
            async loadData(arg) {
                if (arg === 1) {
                    this.ipagination.current = 1;
                }
                this.loading = true
                let params = this.getQueryParams()//查询条件
                params.custCode = this.reqCode;
            },
            // 触发屏幕自适应
            resetScreenSize() {
                let screenWidth = document.body.clientWidth;
                if (screenWidth < 500) {
                    this.scrollTrigger = {x: 800};
                } else {
                    this.scrollTrigger = {};
                }
            },
            showModal(reqCode) {
                this.positionsData = [];
                this.visible = true;
                this.reqCode = reqCode
                this.form.resetFields();
                this.getSelectdData();
            },
            /**
             * 获取查询参数
             * @returns {*}
             */
            getQueryParams() {
                let param = Object.assign({}, this.queryParam);
                param.current = this.ipagination.current;
                param.size = this.ipagination.pageSize;
                return filterObj(param);
            },
            searchReset(num) {
                let that = this;
                if (num !== 0) {
                    that.loadData(1);
                }
                that.selectedRowKeys = [];
                that.selectionRows = [];
                that.selectedKeys = [];
                that.productData = []
                that.categoryData = []
            },
            close() {
                this.searchReset(0);
                this.visible = false;
            },
            handleSubmit() {
                let that = this;
                that.$emit('ok', this.positionsData,this.reqCode);
                that.searchReset(0)
                that.close();
            },
            /**
             * 手动全选/取消全选分类
             * @param selected
             * @param selectedRows
             * @param changeRows
             */
            onSelectAll(selected, selectedRows, changeRows) {
                this.selectedRowKeys = selectedRows.map(row => row.code);
                this.selectionRows = selectedRows
                if (selected) {
                    //todo 选中
                    changeRows.map(row => {
                        this.productData.push(row)
                    })
                } else {
                    //todo 取消选中
                    changeRows.map(row => {
                        this.productData.remove(row)
                    })
                }
            },

            /**
             * 手动勾选/取消分类
             * @param record
             * @param selected
             * @param selectedRows
             * @param nativeEvent
             */
            onSelect(record, selected, selectedRows, nativeEvent) {
                this.selectedRowKeys = selectedRows.map(row => row.code);
                this.selectionRows = selectedRows
                if (selected) {
                    //todo 选中
                    this.productData.push(record)
                } else {
                    //todo 取消选中
                    this.productData.remove(record)
                }


            },
            onSearch() {
                this.loadData(1);
            },

            /**
             * 获取分类树
             * @returns {*}
             */
            queryDepartTree() {
                this.typeLoading  = true
                return postAction( window._CONFIG['domianURL'] + '/goodsclassify/cnGoodsClassify/findPageList').then((res) => {
                    if (res.success) {
                        this.treeData = this.handleStruct(res.result);
                        // 默认展开父节点
                        this.expandedKeys = this.treeData.map(item => item.code)
                    }

                    this.typeLoading  = false
                }).catch(e=>{
                    this.$message.warning(res.message);
                    this.typeLoading  = false
                })
            },
            /**
             * 重构树结构数据
             * @param tree
             * @returns {*}
             */
            handleStruct(tree) {
                return tree.map(t => {
                    const json = {
                        code: t.typeCode,
                        name: t.typeName,
                        // status: t.status,
                        dataType:3,
                        id: t.id,
                        children:t.children
                    }
                    if (json.children) {
                        json.children = this.handleStruct(json.children)
                    }
                    return json
                })
            },
            modalFormOk() {
                this.loadData();
            }
        }
    }
</script>

<style scoped>
    .ant-table-tbody .ant-table-row td {
        padding-top: 10px;
        padding-bottom: 10px;
    }

    #components-layout-demo-custom-trigger .trigger {
        font-size: 18px;
        line-height: 64px;
        padding: 0 24px;
        cursor: pointer;
        transition: color .3s;
    }
</style>
